package com.xuanyuan.atlas.config;

import org.apache.commons.codec.binary.Base64;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

/**
 * @Description：
 * @Author： LUOYUAN
 * @Date： 2020-05-06-15:46
 */

@Configuration
public class RestTemplateConfig
{

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){

        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setInterceptors(Collections.singletonList(new UserAgentInterceptor()));

        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }


    HttpHeaders createHeaders(String username, String password) {
        return new HttpHeaders() {
            {
                final String plainCreds = "admin:admin";
                final byte[] plainCredsBytes = plainCreds.getBytes();
                final byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
                final String base64Creds = new String(base64CredsBytes);

                final HttpHeaders headers = new HttpHeaders();
                headers.add("Authorization", "Basic " + base64Creds);
            }
        };
    }

}
